import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, ssoLogin } from '@/api/login'
import { configSetting } from '@/config'
import router from '@/router'
import { db } from '@/storage'

import type { FormValue } from './type'

import type { UserInfo, LoginResponseTypes } from '@/api'

const userStore = defineStore('user', () => {
  const userInfo = ref<UserInfo>({})
  const token = ref('')
  // 存储权限
  const permission = ref<any>([])
  let userPermissionMap = db.getMap('userPermissionMap') || new Map()

  const setUserInfo = async (user: UserInfo) => {
    userInfo.value = user
    db.set('userInfo', userInfo.value)
  }

  const setToken = async (tokenString: string) => {
    token.value = tokenString
    db.set('token', token.value)
  }

  const setTokenStartTime = async () => {
    db.set('expires', new Date().getTime())
  }

  const setPermission = async (authMenus: string[] | undefined) => {
    permission.value = authMenus
    generaterPermissionMap()
  }
  // 生成PermissionMap
  const generaterPermissionMap = () => {
    const map = new Map()
    if (permission.value.length) {
      permission.value.forEach((item: string) => map.set(item, true))
    }
    userPermissionMap = map
    db.setMap('userPermissionMap', userPermissionMap)
  }

  const permissionAuth = (key: string) => {
    return !!userPermissionMap && !!userPermissionMap.get(key)
  }

  const loginHandler = async ({ userInfo, token }: LoginResponseTypes) => {
    await setToken(token as string)
    await setTokenStartTime()
    await setUserInfo(userInfo as UserInfo)
    await setPermission(userInfo?.permission)

    return router.push({
      name: configSetting.MianLayoutName
    })
  }

  const ssoLoginHandle = ({ token }: Record<string, string>) => {
    return ssoLogin().then((res: LoginResponseTypes) => {
      return loginHandler({ ...res, token }).then(() => res)
    })
  }

  const loginForm = ({ username, password }: FormValue) => {
    return login({ username, password }).then((res: LoginResponseTypes) => {
      return loginHandler({ ...res }).then(() => res)
    })
  }

  const logout = () => {
    return new Promise((resovle): any => {
      db.clear()
      resovle('')
    })
  }

  return {
    userInfo,
    token,
    permission,
    setUserInfo,
    loginForm,
    logout,
    ssoLoginHandle,
    permissionAuth
  }
})

export { userStore }
